<template>
  <div>
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-input
          v-model="searchName"
          placeholder="请输入应聘者姓名"
          style="width: 200px"
          class="filter-item"
        ></el-input>
        <el-select v-model="searchStatus" placeholder="选择状态" clearable class="filter-item">
          <el-option label="待处理" value="待处理"></el-option>
          <el-option label="面试中" value="面试中"></el-option>
          <el-option label="已录用" value="已录用"></el-option>
          <el-option label="已拒绝" value="已拒绝"></el-option>
        </el-select>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="success" @click="handleAdd">添加招聘记录</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" width="80"></el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话" width="120"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="education" label="学历" width="100"></el-table-column>
        <el-table-column prop="department" label="应聘部门" width="120"></el-table-column>
        <el-table-column prop="position" label="应聘职位" width="120"></el-table-column>
        <el-table-column prop="applicationDate" label="申请日期" width="180"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{scope.row.status}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="info" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="form.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                v-model="form.birthDate"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请日期" prop="applicationDate">
              <el-date-picker
                v-model="form.applicationDate"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历" prop="education">
              <el-select v-model="form.education" placeholder="请选择学历">
                <el-option label="高中" value="高中"></el-option>
                <el-option label="专科" value="专科"></el-option>
                <el-option label="本科" value="本科"></el-option>
                <el-option label="硕士" value="硕士"></el-option>
                <el-option label="博士" value="博士"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态">
                <el-option label="待处理" value="待处理"></el-option>
                <el-option label="面试中" value="面试中"></el-option>
                <el-option label="已录用" value="已录用"></el-option>
                <el-option label="已拒绝" value="已拒绝"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="应聘部门" prop="department">
              <el-input v-model="form.department"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="应聘职位" prop="position">
              <el-input v-model="form.position"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog title="招聘记录详情" :visible.sync="detailVisible" width="50%">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ detail.gender }}</el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ formatDate(detail.birthDate) }}</el-descriptions-item>
        <el-descriptions-item label="手机号码">{{ detail.phone }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ detail.email }}</el-descriptions-item>
        <el-descriptions-item label="应聘日期">{{ formatDate(detail.applicationDate) }}</el-descriptions-item>
        <el-descriptions-item label="应聘状态">
          <el-tag :type="getStatusType(detail.status)">{{ detail.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="学历">{{ detail.education }}</el-descriptions-item>
        <el-descriptions-item label="应聘部门">{{ detail.department }}</el-descriptions-item>
        <el-descriptions-item label="应聘职位">{{ detail.position }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    // 邮箱验证规则
    const validateEmail = (rule, value, callback) => {
      if (!/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'));
      } else {
        callback();
      }
    };

    return {
      tableData: [],
      searchName: "",
      searchStatus: "",
      dialogVisible: false,
      dialogTitle: "添加招聘记录",
      isEdit: false,
      form: {
        name: "",
        gender: "男",
        birthDate: "",
        phone: "",
        email: "",
        applicationDate: "",
        status: "待处理",
        education: "",
        department: "",
        position: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "请选择性别", trigger: "change" }
        ],
        birthDate: [
          { required: true, message: "请选择出生日期", trigger: "change" }
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: validateEmail, trigger: "blur" }
        ],
        applicationDate: [
          { required: true, message: "请选择申请日期", trigger: "change" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "change" }
        ],
        education: [
          { required: true, message: "请选择学历", trigger: "change" }
        ],
        department: [
          { required: true, message: "请输入应聘部门", trigger: "blur" }
        ],
        position: [
          { required: true, message: "请输入应聘职位", trigger: "blur" }
        ]
      },
      currentRecordId: null,
      detailVisible: false,
      detail: {}
    };
  },
  created() {
    this.getAllRecords();
  },
  methods: {
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        '待处理': 'info',
        '面试中': 'warning',
        '已录用': 'success',
        '已拒绝': 'danger'
      };
      return statusMap[status] || 'info';
    },

    // 获取所有招聘记录
    getAllRecords() {
      this.$http.get("/api/recruitment_records")
        .then(response => {
          if (response.data.code === 200) {
            this.tableData = response.data.data;
          } else {
            this.$message.error(response.data.msg);
          }
        });
    },

    // 搜索
    handleSearch() {
      if (this.searchName || this.searchStatus) {
        // 获取所有记录后在前端进行筛选
        this.$http.get("/api/recruitment_records")
          .then(response => {
            if (response.data.code === 200) {
              let filteredData = response.data.data;

              // 按姓名筛选
              if (this.searchName) {
                filteredData = filteredData.filter(item =>
                  item.name.includes(this.searchName)
                );
              }

              // 按状态筛选
              if (this.searchStatus) {
                filteredData = filteredData.filter(item =>
                  item.status === this.searchStatus
                );
              }

              this.tableData = filteredData;
            } else {
              this.$message.error(response.data.msg);
            }
          });
      } else {
        this.getAllRecords();
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchName = "";
      this.searchStatus = "";
      this.getAllRecords();
    },

    // 打开添加对话框
    handleAdd() {
      this.isEdit = false;
      this.dialogTitle = "添加招聘记录";
      this.form = {
        name: "",
        gender: "男",
        birthDate: "",
        phone: "",
        email: "",
        applicationDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
        status: "待处理",
        education: "",
        department: "",
        position: ""
      };
      this.dialogVisible = true;
    },

    // 打开编辑对话框
    handleEdit(row) {
      this.isEdit = true;
      this.dialogTitle = "编辑招聘记录";
      this.currentRecordId = row.recordId;
      this.form = { ...row };
      this.dialogVisible = true;
    },

    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isEdit) {
            // 更新记录
            this.$http.put(`/api/recruitment_records/${this.currentRecordId}`, JSON.stringify(this.form), {
              headers: {
                'Content-Type': 'application/json'
              }
            }).then(response => {
                if (response.data.code === 200) {
                  this.$message.success("更新成功");
                  this.dialogVisible = false;
                  this.getAllRecords();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          } else {
            // 添加记录
            this.$http.post("/api/recruitment_records", JSON.stringify(this.form), {
              headers: {
                'Content-Type': 'application/json'
              }
            }).then(response => {
                if (response.data.code === 200) {
                  this.$message.success("添加成功");
                  this.dialogVisible = false;
                  this.getAllRecords();
                } else {
                  this.$message.error(response.data.msg);
                }
              });
          }
        }
      });
    },

    // 删除记录
    handleDelete(row) {
      this.$confirm('确认删除该招聘记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`/api/recruitment_records/${row.recordId}`)
          .then(response => {
            if (response.data.code === 200) {
              this.$message.success("删除成功");
              this.getAllRecords();
            } else {
              this.$message.error(response.data.msg);
            }
          });
      });
    },

    // 查看详情
    handleView(row) {
      this.detail = { ...row };
      this.detailVisible = true;
    },

    // 格式化日期
    formatDate(date) {
      if (date) {
        return date.slice(0, 10);
      }
      return "";
    }
  }
};
</script>
